package com.zhenwei.zscm.config.interceptors;

import com.zhenwei.zscm.common.exception.CustomException;
import com.zhenwei.zscm.common.base.RestMsg;
import com.zhenwei.zscm.common.base.UserContext;
import com.zhenwei.zscm.common.utils.Linq;
import com.zhenwei.zscm.model.dto.roleAuth.RoleAuthDTO;
import com.zhenwei.zscm.model.dto.user.UserDTO;
import com.zhenwei.zscm.repo.RoleAuthRepo;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class PermissionInterceptor implements HandlerInterceptor {

    @Autowired
    private RoleAuthRepo roleAuthRepo;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;

            // 获取当前方法的权限注解
            RequestMapping classRequestMapping = handlerMethod.getBeanType().getAnnotation(RequestMapping.class);
            String prefix = "";
            if (classRequestMapping != null) {
                prefix = classRequestMapping.value()[0];
            }

            // 获取方法上的 RequestMapping 注解
            RequestMapping methodRequestMapping = handlerMethod.getMethodAnnotation(RequestMapping.class);
            String subfix = "";
            if (methodRequestMapping != null) {
                subfix = methodRequestMapping.value()[0];
            }
            String method = request.getMethod();
            String apiUrl= method + "->" + prefix + subfix;

            UserDTO currentUser = UserContext.getCurrentUser();
            RoleAuthDTO roleAuth = roleAuthRepo.getRoleAuth(currentUser.getRole());
            var hasPermission = Linq.exists(roleAuth.getAuthApi(), x->x.getApiUrl().equals(apiUrl));
            if(!hasPermission) {
                throw new CustomException(RestMsg.NO_AUTH_ACCESS);
            }
        }
        return true;
    }
}
